var $customerInformation = $('#customerInformation');

$(function(){
    customerInformationInit();
    $(".time").datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    getProvince();
});

// 渲染省市列表
function getProvince() {
    let provinceNames = ['<option value="init">--请选择--</option>'];
    $.each(cityJson[0], function(key, value){
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#province').html(provinceNames.join(''));
    getCity($('#province').val());
}
// 根据省获取市
function getCity(provinceId) {
    $('#city').html('');
    let key = '0,'+provinceId;
    let cityNames = ['<option value="init">--请选择--</option>'];
    if(provinceId != 'init'){
        $.each(cityJson[key], function(key, value){
            cityNames.push('<option value="' + key + '">' + value + '</option>')
        });
    }
    $('#city').html(cityNames.join(''));
    getOrangin($('#province').val(), $('#city').val());
}
// '切换省'
function changeProvince() {
    getCity($('#province').val());
    getOrangin($('#province').val(), $('#city').val());
}

// 获取区
function getOrangin(provinceId, cityId) {
    $('#county').html('');
    let key = '0,'+provinceId+ ',' + cityId;
    let oranginNames = ['<option value="init">--请选择--</option>'];
    if(provinceId != 'init' && cityId != 'init'){
        $.each(cityJson[key], function(key, value){
            oranginNames.push('<option value="' + key + '">' + value + '</option>')
        });
    }
    $('#county').html(oranginNames.join(''));
}

// 切换城市
function changeCitys() {
    getOrangin($('#province').val(), $("#city").val());
}

function customerInformationInit(){
    //先销毁表格
    $customerInformation.bootstrapTable('destroy');
    $customerInformation.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/csd/customerInfo/selectCustomerInfoList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerInfoId',
        idField: 'customerInfoId',
        serverSelected: true,// 开启后端分页记住已选项功能
        serverSelectedField: 'customerInfoId',// 已选项的唯一识别主键
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        // fixedColumns: true,     // 冻结列
        // fixedNumber: 4,         // 左侧固定列
        queryParams:function(params) {
            params.pageSize = params.limit;
            params.pageIndex = (params.offset / params.limit) + 1;
            params.sortName = params.sort; //排序列名
            params.sortOrder = params.order;//排序方式

            // 高级筛选
            params.enterpriseName = $("#enterpriseNameScreen").val();//企业名称
            params.registStatus = $("#registStatusScreen").val();//登记状态：在业/注销
            params.legalPerson = $("#legalPersonScreen").val();//法定代表人
            params.registCapital = $("#registCapitalScreen").val();//注册资本
            params.establishDateStart = $("#establishDateStart").val();//成立日期开始时间
            params.establishDateEnd = $("#establishDateEnd").val();//成立日期结束时间
            params.approvalDateStart = $("#approvalDateStart").val();//核准日期开始时间
            params.approvalDateEnd = $("#approvalDateEnd").val();//核准日期结束时间
            params.provice = $("#proviceSelect").val();//所属省份
            params.city = $("#citySelect").val();//所属城市
            params.district = $("#districtSelect").val();//所属区县
            params.socialCode = $("#socialCodeScreen").val();//统一社会信用代码
            params.phone = $("#phoneScreen").val();//电话
            params.email = $("#emailScreen").val();//邮箱
            params.taxpayerCode = $("#taxpayerCodeScreen").val();//纳税人识别号
            params.registCode = $("#registCodeScreen").val();//注册号
            params.orgCode = $("#orgCodeScreen").val();//组织机构代码
            params.insuredTotal = $("#insuredTotalScreen").val();//参保人数
            params.enterpriseType = $("#enterpriseTypeScreen").val();//企业类型
            params.industryType = $("#companySelect").val();//所属行业
            params.oldName = $("#oldNameScreen").val();//曾用名
            params.englishName = $("#englishNameScreen").val();//英文名
            params.enterpriseAddress = $("#enterpriseAddressScreen").val();//企业地址
            params.website = $("#websiteScreen").val();//网址
            params.reportSite = $("#reportSiteScreen").val();//最新年报地址
            params.business = $("#businessScreen").val();//经营范围



            return params;
        },//查询参数
        columns: [
            {title: '选择', field: 'name',align: 'center', valign: 'middle',checkbox:'true'},
            {title: '客户名称', field: 'enterpriseName',align: 'center', valign: 'middle'},
            {title: '信用代码', field: 'socialCode', align: 'center', valign: 'middle'},
            // {title: '客户标签', field: 'customerTag', align: 'center', valign: 'middle'},
            // {title: '所有人', field: 'userName', align: 'center', valign: 'middle'},
            // {title: '客户来源', field: 'customerSource', align: 'center', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'center', events: operateEvents, formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000"){
                var obj = {
                    "rows":result.data,
                    "total": result.totalRecords,
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index){
    let html = '';
    html +='<button type="button" class="btn btn-default" id="detailWorkLog" onclick="customerDetail(\''+row.customerInfoId+'\')">详细</button>';
    //html += '<button type="button" class="btn btn-default" id="editRemark">调整</button>';
    //html += '<button type="button" class="btn btn-default" id="editRemark">分配</button>';

    return html;
}

window.operateEvents = {

};

function customerDetail(customerInfoId){
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '客户详情',
        url : "front/csd/customerInfo/customerDetail?customerInfoId="+customerInfoId,
    }, true);
}


function exportExcel() {

}

//打开高级筛选弹框
function openFilterContainer(){
    $("#closeFilter").show();
    $("#openFilter").hide();
    $("#filterFilesContainer").slideDown();
    // $("#filterFilesContainer").show();
}
//关闭高级筛选弹框
function closeFilterContainer(){
    $("#openFilter").show();
    $("#closeFilter").hide();
    $("#filterFilesContainer").slideUp();
    // $("#filterFilesContainer").hide();
}
//点击高级筛选切换显示隐藏
function showToggle(){
    if($("#filterFilesContainer").is(":hidden")){
        openFilterContainer()
    }else{
        closeFilterContainer()
    }
}

/**
 * 功能：导出
 */
function exportData() {
    var url = "/csd/customerInfo/exportExcel";
    window.location.href = encodeURI(encodeURI(url));
}
function importProductFun() {
    $('#importFollowModal').modal('show');
    $(".btn-detail").attr("disabled",false);
}
/**
 * 导入
 */
function importFollow() {
    if(!document.getElementById('importFollowFile').files[0]){
        $.alert({
            title: '温馨提示',
            content: '请选择文件！',
        });
        return;
    }
    $(".btn-detail").attr("disabled",true);
    var fileName = document.getElementById('importFollowFile').files[0].name;
    var fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    var formData = new FormData();
    //接口接收参数 键值形式 添加到formData中
    formData.append("file",$("#importFollowFile")[0].files[0]);
    if(fileName!="" && (fileType.toLocaleUpperCase()==".XLSX"||fileType.toLocaleUpperCase()==".XLS")){
        $.ajax({
            url: '/csd/customerInfo/uploadExcel',
            type: 'POST',
            dataType:"json",
            contentType:false,
            data: formData,
            processData: false,
            success:(function(data) {
                if(data.code == "000000"){
                    $(".btn-detail").attr("disabled",false);
                    if(data.data.code==0){
                        $.alert("导入成功");
                        $customerInformation.bootstrapTable('refresh');
                    }else if(data.data.code==1){``;
                        $.alert(data.data.msg)
                    }
                    $("#importFollowFile").val("");
                }else{
                    $.alert("导入失败");
                    $("#importFollowFile").val("");
                }
            }),
            error:(function() {
                $.alert("导入出错！");
                $("#importContractFile").val("");
            })
        });




    } else {
        $.alert({
            title: '温馨提示',
            content: '请上传.xlsx或.xls文件！',
        });
    }
}

function addFormModal(){
    $('.formItem').val('');
    $('#province').val('init');
    $('#city').val('init');
    $('#county').val('init');
    $('#addContactForm').modal('show')
}

function addCustomer() {
    if($('#enterpriseName').val() == ''){
        $.alert('企业名称不能为空');
        return;
    }
    if($('#socialCode').val() == ''){
        $.alert('统一社会信用代码不能为空');
        return;
    }

    let provice = $("#province").val() == 'init'?' ':$("#province option:selected").text();
    let city = $("#city").val() == 'init'?' ':$("#city option:selected").text();
    let district = $("#county").val() == 'init'?' ':$("#county option:selected").text();

    let formData = {
        enterpriseName:$('#enterpriseName').val(),
        registStatus:$('#registStatus').val(),
        legalPerson:$('#legalPerson').val(),
        registCapital:$('#registCapital').val(),
        establishDate:$('#establishDate').val(),
        approvalDate:$('#approvalDate').val(),
        provice:provice,
        city:city,
        district:district,
        phone:$('#phone').val(),
        morePhone:$('#morePhone').val(),
        email:$('#email').val(),
        moreEmail:$('#moreEmail').val(),
        socialCode:$('#socialCode').val(),
        taxpayerCode:$('#taxpayerCode').val(),
        registCode:$('#registCode').val(),
        orgCode:$('#orgCode').val(),
        insuredTotal:$('#insuredTotal').val(),
        enterpriseType:$('#enterpriseType').val(),
        industryType:$('#industryType').val(),
        oldName:$('#oldName').val(),
        englishName:$('#englishName').val(),
        website:$('#website').val(),
        enterpriseAddress:$('#enterpriseAddress').val(),
        reportSite:$('#reportSite').val(),
        business:$('#business').val(),
    };
    $.ajax({
        url: '/csd/customerInfo/addCustomerInfo',
        type: 'POST',
        dataType:"json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(formData),
        success:(function(data) {
            if(data.code == "000000"){
                $('#addContactForm').modal('hide');
                customerInformationInit();
            }else{
                alert("加载失败！");
            }
        }),
        error:(function() {
            alert("加载失败！");
        })
    });
}


// 所有行业 /csd/customerInfo/selectIndustryTypeList
function selectIndustryTypeList() {
    $.ajax({
        url:"/csd/customerInfo/selectIndustryTypeList",
        type:"post",
        success:function (data) {

            if(data.code==='000000'){
                let html='<option value="">请选择</option>';
                data.data.map(function (item) {
                    html += '<option value="' + item.industryType + '">' + item.industryType + '</option>';
                });
                $("#companySelect").html("");
                $('#companySelect').append(html);
                $('#companySelect').selectpicker('refresh');
            }else{
                $.alert(data.message)
            }
        },
        error:function (err) {
            $.alert(err.message)
        }
    })
}
selectIndustryTypeList(); //所有行业


// 省份信息 6. /csd/customerInfo/selectProviceList
function selectProviceList() {
    $.ajax({
        url:"/csd/customerInfo/selectProviceList",
        type:"post",
        success:function (data) {

            if(data.code==='000000'){
                let html='<option value="">请选择</option>';
                data.data.map(function (item) {
                    html += '<option value="' + item.provice + '">' + item.provice + '</option>';
                });
                $("#proviceSelect").html("");
                $('#proviceSelect').append(html);
                $('#proviceSelect').selectpicker('refresh');
            }else{
                $.alert(data.message)
            }
        },
        error:function (err) {
            $.alert(err.message)
        }
    })
}

selectProviceList(); //省份信息


function changeProvice() {
    selectCityByProvice($("#proviceSelect").val())
}


// 所属城市 /csd/customerInfo/selectCityByProvice
function selectCityByProvice(provice) {
    $.ajax({
        url:"/csd/customerInfo/selectCityByProvice",
        type:"post",
        data:{
            provice
        },
        success:function (data) {

            if(data.code==='000000'){
                let html='<option value="">请选择</option>';
                data.data.map(function (item) {
                    html += '<option value="' + item.city + '">' + item.city + '</option>';
                });
                $("#citySelect").html("");
                $('#citySelect').append(html);
                $('#citySelect').selectpicker('refresh');
            }else{
                $.alert(data.message)
            }
        },
        error:function (err) {
            $.alert(err.message)
        }
    })
}


function changeCity() {
    selectDistrictByProviceCity($("#proviceSelect").val(),$("#citySelect").val())
}


// 所属区县 /csd/customerInfo/selectDistrictByProviceCity
function selectDistrictByProviceCity(provice,city) {
    $.ajax({
        url:"/csd/customerInfo/selectDistrictByProviceCity",
        type:"post",
        data:{
            provice,
            city
        },
        success:function (data) {

            if(data.code==='000000'){
                let html='<option value="">请选择</option>';
                data.data.map(function (item) {
                    html += '<option value="' + item.district + '">' + item.district + '</option>';
                });
                $("#districtSelect").html("");
                $('#districtSelect').append(html);
                $('#districtSelect').selectpicker('refresh');
            }else{
                $.alert(data.message)
            }
        },
        error:function (err) {
            $.alert(err.message)
        }
    })
}


// 提交筛选
function searchSceenList() {
    $customerInformation.bootstrapTable('refresh');
    closeFilterContainer()
}

function resetAllData() {
    $('input').val('');
    $('select').val('');
    selectCityByProvice('');
    selectDistrictByProviceCity('','');
    $('select').selectpicker('refresh');
    $customerInformation.bootstrapTable('refresh');
}